﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace MachineBuildingSystem
{
    public partial class RegistrationFeeUC : UserControl
    {
        private string m_CurrentUser = "";
        private string m_Password = "";
        private List<long> m_ActionList = new List<long>();

        private OrderInfo m_CurrentOrder = new OrderInfo ();
        private long m_CurrentSaleOutId = -1;
        private List<ExpenseTypeData> m_ExpenseTypeDataList = new List<ExpenseTypeData>();
        //出库单DT
        private DataTable m_SaleOutsDT = new DataTable ();
        //费用类别DT
        private DataTable m_RegistrationFeeDT = new DataTable();
        public RegistrationFeeUC()
        {
            InitializeComponent();
        }

        private void RegistrationFeeUC_Load(object sender, EventArgs e)
        {
            if (!backgroundWorker_Registration.IsBusy)
                backgroundWorker_Registration.RunWorkerAsync();
        }

        private void InitSaleOutDT()
        {
            m_SaleOutsDT = new DataTable();
            m_SaleOutsDT.Columns.Add("id", typeof(long));
            m_SaleOutsDT.Columns.Add("customerCode", typeof(string));
            m_SaleOutsDT.Columns.Add("customerName", typeof(string));
            m_SaleOutsDT.Columns.Add("outDate", typeof(DateTime));
            m_SaleOutsDT.Columns.Add("outQuantity", typeof(decimal));
            m_SaleOutsDT.Columns.Add("projectName", typeof(string));
            m_SaleOutsDT.Columns.Add("constructSite", typeof(string));
            m_SaleOutsDT.Columns.Add("slump", typeof(string));
            m_SaleOutsDT.Columns.Add("areaName", typeof(string));
            m_SaleOutsDT.Columns.Add("unitPrice", typeof(decimal));
            m_SaleOutsDT.Columns.Add("money", typeof(decimal));
            m_SaleOutsDT.Columns.Add("finalMoney", typeof(decimal));
            m_SaleOutsDT.Columns.Add("finalPrice", typeof(decimal));
            m_SaleOutsDT.Columns.Add("invoiceMoney", typeof(decimal));
            m_SaleOutsDT.Columns.Add("invoicePrice", typeof(decimal));
            m_SaleOutsDT.Columns.Add("driverName", typeof(string));
            m_SaleOutsDT.Columns.Add("carCode", typeof(string));
            m_SaleOutsDT.Columns.Add("deliveryDate", typeof(string));
        }

        private void InitRegistrationFeeDT()
        {
            m_RegistrationFeeDT = new DataTable();
            m_RegistrationFeeDT.Columns.Add("Checked", typeof(bool));
            m_RegistrationFeeDT.Columns.Add("id",typeof(long));
            m_RegistrationFeeDT.Columns.Add("expenseDate", typeof(string));
            m_RegistrationFeeDT.Columns.Add("expenseName", typeof(string));
            m_RegistrationFeeDT.Columns.Add("quantity", typeof(decimal));
            m_RegistrationFeeDT.Columns.Add("price", typeof(decimal));
            m_RegistrationFeeDT.Columns.Add("moneys", typeof(decimal));
            m_RegistrationFeeDT.Columns.Add("remarks", typeof(string));
            m_RegistrationFeeDT.Columns.Add("status", typeof(string));
            m_RegistrationFeeDT.Columns.Add("checker", typeof(string));
            m_RegistrationFeeDT.Columns.Add("checkDate", typeof(string));
            m_RegistrationFeeDT.Columns.Add("driverName", typeof(string));
            m_RegistrationFeeDT.Columns.Add("carCode", typeof(string));
            m_RegistrationFeeDT.Columns.Add("deliveryDate", typeof(string));
            m_RegistrationFeeDT.Columns.Add("isAuto", typeof(string));
            m_RegistrationFeeDT.Columns.Add("invalid", typeof(string));
            m_RegistrationFeeDT.Columns.Add("sheetMaker", typeof(string));
            m_RegistrationFeeDT.Columns.Add("createDate", typeof(string));
        }

        public void RefreshRegistrationFee(string currentUser, string password, List<long> actionList, OrderInfo order)
        {
            m_CurrentOrder = order;
            InitSaleOutDT();
            InitRegistrationFeeDT();
            m_CurrentUser = currentUser;
            m_Password = password;
            m_ActionList = actionList;
            try
            {
                m_ExpenseTypeDataList = DataHelper.GetExpenseType(m_CurrentUser, m_Password);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "初始化费用类别异常：" + ex.Message);
                return;
            }
            if (!backgroundWorker.IsBusy)
                backgroundWorker.RunWorkerAsync();
        }

        #region 出库单
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<SaleOutsData> saleOutsDataList = new List<SaleOutsData>();
            try
            {
                saleOutsDataList = DataHelper.GetSaleOutsByOrder(m_CurrentUser, m_Password, m_CurrentOrder.id);
            }
            catch
            {
                throw;
            }
            e.Result = saleOutsDataList;
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;
            if (e.Error != null)
            {
                LogHelper.error("加载费用信息错误：" + e.Error.Message);
                MessageBox.Show(this, e.Error.Message);
                return;
            }
            m_SaleOutsDT.Clear();
            this.gdcSaleOuts.DataSource = m_SaleOutsDT;
            List<SaleOutsData> saleOutsDataList = e.Result as List<SaleOutsData>;
            if (saleOutsDataList == null || saleOutsDataList.Count == 0)
                return;
            BindDataSaleOut(saleOutsDataList);
            //加载费用列表
            if (!backgroundWorker_Registration.IsBusy)
                backgroundWorker_Registration.RunWorkerAsync();
        }

        private void BindDataSaleOut(List<SaleOutsData> saleOutsDataList)
        {
            try
            {
                foreach (SaleOutsData saleOuts in saleOutsDataList)
                {
                    //if (saleOuts.outQuantity < 0)
                    //    continue;
                    m_SaleOutsDT.Rows.Add(saleOuts.id, saleOuts.customerCode, saleOuts.customerName,
                        saleOuts.outDate, saleOuts.outQuantity, saleOuts.projectName, saleOuts.constructSite,
                        saleOuts.slump, saleOuts.areaName, saleOuts.unitPrice, saleOuts.money, saleOuts.finalMoney,
                        saleOuts.finalPrice, saleOuts.invoiceMoney, saleOuts.invoicePrice, 
                        saleOuts.driverName, saleOuts.carCode, saleOuts.deliveryDate);
                }
                this.gdcSaleOuts.DataSource = m_SaleOutsDT;
            }
            catch (Exception ex)
            {
                LogHelper.error("绑定出库单信息列表异常：" + ex.ToString());
            }
        }
        #endregion

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.FeeAdd))
            {
                MessageBox.Show(this, "该用户无添加费用权限！");
                return;
            }
            DataRow currentRow = this.gdvSaleOuts.GetFocusedDataRow();
            //if (currentRow == null)
            //{
            //    MessageBox.Show(this, "请选择需要费用登记的出库单！");
            //    return;
            //}
            if (currentRow != null && decimal.Parse(currentRow["outQuantity"].ToString()) < 0)
            {
                MessageBox.Show(this, "红冲的出库单不能添加费用！");
                return;
            }
            try
            {
                RegistrationFeeAddForm form = new RegistrationFeeAddForm();
                form.CurrentUser = m_CurrentUser;
                form.Password = m_Password;
                form.SaleOrder = m_CurrentOrder;
                form.SaleOutId = currentRow == null ? -1 : Convert.ToInt64(currentRow["id"]);
                form.CarCode = currentRow == null ? "" : currentRow["carCode"].ToString();
                form.Driver = currentRow == null ? "" : currentRow["driverName"].ToString();
                form.DeliDate = currentRow == null ? DateTime.MinValue : Convert.ToDateTime(currentRow["deliveryDate"].ToString());

                form.ExpenseTypeDataList = m_ExpenseTypeDataList;

                if (form.ShowDialog() == DialogResult.OK)
                {
                    //刷新费用登记列表
                    if (!backgroundWorker_Registration.IsBusy)
                        backgroundWorker_Registration.RunWorkerAsync();
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("添加费用异常:" + ex.ToString() + ",deliveryDate:" + currentRow["deliveryDate"]);
                MessageBox.Show("添加费用异常：" + ex.Message);
            }
          
        }

        public delegate void RegistrationFeeCloseEventHandler(object sender, EventArgs e);
        public event RegistrationFeeCloseEventHandler RegistrationFeeCloseEvent;
        private void btnClose_Click(object sender, EventArgs e)
        {
            if (RegistrationFeeCloseEvent != null)
                RegistrationFeeCloseEvent(this, e);
        }

        //出库单变化费用登记跟着变化
        private void gdvSaleOuts_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DataRow currentRow = this.gdvSaleOuts.GetFocusedDataRow();
            if (currentRow == null)
                return;
            m_CurrentSaleOutId = Convert.ToInt64(currentRow["id"]);
            if (rgpExpenseType.SelectedIndex == (int)ExpenseTypeEnum.ExpenseAll ||
                rgpExpenseType.SelectedIndex == (int)ExpenseTypeEnum.ExpenseEntire)
                return;

            //根据出库单id获取费用登记信息
            if (!backgroundWorker_Registration.IsBusy)
                backgroundWorker_Registration.RunWorkerAsync();
        }

        #region 费用
        private void backgroundWorker_Registration_DoWork(object sender, DoWorkEventArgs e)
        {
            List<SaleExpenseData> saleExpenseList = new List<SaleExpenseData>();
            try
            {
                //货款直接由发货单数据组织起来
                if (rgpExpenseType.SelectedIndex == (int)ExpenseTypeEnum.Payment)
                {
                    DataRow currentRow = this.gdvSaleOuts.GetFocusedDataRow();
                    if (currentRow == null)
                        return;
                    SaleExpenseData data = new SaleExpenseData();
                    data.expenseDate = Convert.ToDateTime(currentRow["outDate"]);
                    data.expenseName = "货款";
                    data.quantity = Convert.ToDecimal(currentRow["outQuantity"]);
                    data.price = Convert.ToDecimal(currentRow["finalPrice"]);
                    data.moneys = Convert.ToDecimal(currentRow["finalMoney"]);
                    data.driverName = currentRow["driverName"].ToString();
                    data.carCode = currentRow["carCode"].ToString();
                    data.deliveryDate = Convert.ToDateTime(currentRow["deliveryDate"].ToString());
                    saleExpenseList.Add(data);
                }
                else
                {
                    saleExpenseList = DataHelper.GetSaleExpense(m_CurrentUser, m_Password, m_CurrentSaleOutId,
                        m_CurrentOrder.id, rgpExpenseType.SelectedIndex);
                }
            }
            catch
            {
                throw;
            }
            e.Result = saleExpenseList;
        }

        private void backgroundWorker_Registration_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;
            if (e.Error != null)
            {
                LogHelper.error("加载费用信息错误：" + e.Error.Message);
                MessageBox.Show(this, e.Error.Message);
                return;
            }
            m_RegistrationFeeDT.Clear();
            this.gdcRegistration.DataSource = m_RegistrationFeeDT;
            List<SaleExpenseData> saleExpenseList = e.Result as List<SaleExpenseData>;
            if (saleExpenseList == null || saleExpenseList.Count == 0)
                return;
            BindData(saleExpenseList);
        }

        //绑定列表
        private void BindData(List<SaleExpenseData> saleExpenseList)
        {
            try
            {
                foreach (SaleExpenseData saleExpense in saleExpenseList)
                    m_RegistrationFeeDT.Rows.Add(false, saleExpense.id, saleExpense.expenseDate.ToString("yyyy-MM-dd HH:mm:ss"), saleExpense.expenseName,
                        saleExpense.quantity, saleExpense.price, saleExpense.moneys, saleExpense.remarks,
                        saleExpense.status == (int)ExpenseCheckEnum.NotPass ? "不通过" :
                        (saleExpense.status == (int)ExpenseCheckEnum.Audited ? "已审核" : "未审核"), saleExpense.checker,
                        saleExpense.checkDate == DateTime.MinValue ? "" : saleExpense.checkDate.ToString("yyyy-MM-dd HH:mm:ss"),
                        saleExpense.driverName, saleExpense.carCode,
                        saleExpense.deliveryDate == DateTime.MinValue ? "" : saleExpense.deliveryDate.ToString("yyyy-MM-dd HH:mm:ss"),
                        saleExpense.isAuto == true ? "是" : "否",
                        saleExpense.invalid == true ? "是" : "否",
                        saleExpense.sheetMaker,
                        saleExpense.createDate == DateTime.MinValue ? "" : saleExpense.createDate.ToString("yyyy-MM-dd HH:mm:ss"));
                this.gdcRegistration.DataSource = m_RegistrationFeeDT;
            }
            catch (Exception ex)
            {
                LogHelper.error("绑定费用登记信息列表异常：" + ex.ToString());
            }
        }
        #endregion

        //费用类型变化时重新加载数据
        private void rgpExpenseType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rgpExpenseType.SelectedIndex == (int)ExpenseTypeEnum.Payment)
            {
                this.btnDelete.Enabled = false;
                this.lciCheck.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                gdcStatus.Visible = false;
                gdcChecker.Visible = false;
                gdcCheckDate.Visible = false;
                gdcSheetMaker.Visible = false;
                gdcCreateDate.Visible = false;
            }
            else
            {
                gdcStatus.Visible = true;
                gdcChecker.Visible = true;
                gdcCheckDate.Visible = true;
                this.btnDelete.Enabled = true;
                gdcSheetMaker.Visible = true;
                gdcCreateDate.Visible = true;
                this.lciCheck.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            }
            if (!backgroundWorker_Registration.IsBusy)
                backgroundWorker_Registration.RunWorkerAsync();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.FeeDel))
            {
                MessageBox.Show(this, "该用户无删除费用权限！");
                return;
            }
            DataRow currentRow = this.gdvRegistration.GetFocusedDataRow();
            if (currentRow == null)
                return;
            //费用审核后不能删除
            if (currentRow["status"].ToString() == "已审核")
            {
                MessageBox.Show(this, "该费用已审核，不能删除！");
                return;
            }
            long expenseId = Convert.ToInt64(currentRow["id"]);
            if (DialogResult.Yes == MessageBox.Show(this, "是否确定删除当前选择的费用记录？", "", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                try
                {
                    if (!DataHelper.DeleteSaleExpense(m_CurrentUser, m_Password, expenseId))
                        return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "删除费用失败：" + ex.Message);
                    return;
                }
                MessageBox.Show(this, "删除成功！");
                //刷新
                if (!backgroundWorker_Registration.IsBusy)
                    backgroundWorker_Registration.RunWorkerAsync();
            }
        }

        private void btnAudited_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.FeeCheck))
            {
                MessageBox.Show(this, "该用户无审核费用权限！");
                return;
            }
            List<DataRow> selectedRowList = GetSelectedRowList();
            if (selectedRowList == null || selectedRowList.Count == 0)
                return;
            foreach (DataRow row in selectedRowList)
            {
                string status = row["status"].ToString();
                if (status == "已审核")
                {
                    MessageBox.Show(this, "勾选列表中存在已审核的费用，不能审核！");
                    return;
                }
            }
            try
            {
                List<Dictionary<string, object>> list = 
                    GetDealSaleExpenseDic((int)ExpenseCheckEnum.Audited, selectedRowList);
                CGlobal.strSwapJsonData = JsonConvert.SerializeObject(list);
                if (!DataHelper.DealSaleExpense(m_CurrentUser, m_Password))
                    return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "审核失败:" + ex.Message);
                return;
            }
            MessageBox.Show(this, "审核成功！");
            //刷新
            if (!backgroundWorker_Registration.IsBusy)
                backgroundWorker_Registration.RunWorkerAsync();
        }

        private void btnNotAudited_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.FeeUnCheck))
            {
                MessageBox.Show(this, "该用户无审核费用权限！");
                return;
            }
            List<DataRow> selectedRowList = GetSelectedRowList();
            if (selectedRowList == null || selectedRowList.Count == 0)
                return;
            foreach (DataRow row in selectedRowList)
            {
                string status = row["status"].ToString();
                bool isAuto = row["isAuto"].ToString() == "是" ? true : false;
                if (isAuto)
                {
                    MessageBox.Show(this, "勾选列表中存在自动生成的费用，不能弃审！");
                    return;
                }
                if (status == "未审核")
                {
                    MessageBox.Show(this, "勾选列表中存在未审核的费用，不能弃审！");
                    return;
                }
                if (status == "不通过")
                {
                    MessageBox.Show(this, "勾选列表中存在审核不通过的费用，不能弃审！");
                    return;
                }
            }
            try
            {
                List<Dictionary<string, object>> list =
                    GetDealSaleExpenseDic((int)ExpenseCheckEnum.NotAudited, selectedRowList);
                CGlobal.strSwapJsonData = JsonConvert.SerializeObject(list);
                if (!DataHelper.DealSaleExpense(m_CurrentUser, m_Password))
                    return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "弃审失败:" + ex.Message);
                return;
            }
            MessageBox.Show(this, "弃审成功！");
            //刷新
            if (!backgroundWorker_Registration.IsBusy)
                backgroundWorker_Registration.RunWorkerAsync();
        }

        private void btnNotPass_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.FeeCheckUnPass))
            {
                MessageBox.Show(this, "该用户无审核费用权限！");
                return;
            }
            List<DataRow> selectedRowList = GetSelectedRowList();
            if (selectedRowList == null || selectedRowList.Count == 0)
                return;
            foreach (DataRow row in selectedRowList)
            {
                string status = row["status"].ToString();
                if (status == "不通过")
                {
                    MessageBox.Show(this, "勾选列表中存在审核不通过的费用，不能不通过！");
                    return;
                }
                if (status == "已审核")
                {
                    MessageBox.Show(this, "勾选列表中存在已审核的费用，不能不通过！");
                    return;
                }
            }
            try
            {
                List<Dictionary<string, object>> list =
                    GetDealSaleExpenseDic((int)ExpenseCheckEnum.NotPass, selectedRowList);
                CGlobal.strSwapJsonData = JsonConvert.SerializeObject(list);
                if (!DataHelper.DealSaleExpense(m_CurrentUser, m_Password))
                    return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "审核不通过失败:" + ex.Message);
                return;
            }
            MessageBox.Show(this, "审核不通过成功！");
            //刷新
            if (!backgroundWorker_Registration.IsBusy)
                backgroundWorker_Registration.RunWorkerAsync();
        }

        private List<DataRow> GetSelectedRowList()
        {
            List<DataRow> selectedRowList = new List<DataRow>();
            for (int i = 0; i < gdvRegistration.RowCount; i++)
            {
                DataRow row = gdvRegistration.GetDataRow(i);
                if (Convert.ToBoolean(row["Checked"]) == true)
                    selectedRowList.Add(row);
            }
            if (selectedRowList.Count == 0)
            {
                MessageBox.Show(this, "请勾选费用单据!");
                return null;
            }
            return selectedRowList;
        }

        private List<Dictionary<string, object>> GetDealSaleExpenseDic(int status, List<DataRow> selectedRowList)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow row in selectedRowList)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                long id = Convert.ToInt64(row["id"]);
                dic.Add("id", id);
                dic.Add("status", status);
                list.Add(dic);
            }
            return list;
        }

        private void repositoryItemCheckEdit_CheckedChanged(object sender, EventArgs e)
        {
            gdvRegistration.CloseEditor();
            gdvRegistration.UpdateCurrentRow();
            DataTable dt = this.gdcRegistration.DataSource as DataTable;
            gdcRegistration.RefreshDataSource();
        }

        private void gdvSaleOuts_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gdvRegistration_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
    }
}
